var router = require('koa-router')({
    prefix: '/project/:id'
});
var models = require('./../../../models');
var q = require('q');


router.get('/sectionconfig', function* (next) {
    var sections = yield this.state.project.getSectionConfigs();
    var coorDiffs = yield this.state.project.getCoorDiffs();
    this.render('project/section.config.jade', {
        project: this.state.project,
        sections: sections,
        url: this.request.url,
        caculated: coorDiffs.length > 0
    });
});

router.post('/sectionconfig', function* (next) {
    var section = this.request.body;
    yield models.SectionConfig.create(section);
    this.redirect(`/project/${this.params.id}/sectionconfig`);
});

router.get('/sectionconfig/:sectionId/delete', function* (next) {
    var section = yield models.SectionConfig.findById(parseInt(this.params.sectionId));
    yield section.destroy();
    this.redirect(`/project/${this.params.id}/sectionconfig`);
});

router.get('/sectionconfig/caculateDiff', function* (next) {
    var prjId = this.state.project.id;
    yield models.CoorDiff.destroy({
        where: {
            prjId: prjId
        }
    });
    yield models.AngleCoorDiff.destroy({
        where: {
            prjId: prjId
        }
    });
    var preDefinedNames = {
        pb0: ['pb', 'pb1'],
        st0: ['st', 'st1'],
        pf0: ['pf', 'pf1'],
        ph0: ['ph'],
    };//数组的第一个点为顶管中心坐标
    var sections = yield this.state.project.getSectionConfigs();
    for (var key in preDefinedNames) {
        var center = sections.find(s=> { return s.name === key; });//先拿到中心
        if (center) {
            var names = preDefinedNames[key];
            for (var i = 0; i < names.length; i++) {
                var name = names[i];
                var pt = sections.find(s=> { return s.name === name; });
                if (pt) {
                    yield models.CoorDiff.create({
                        prjId: prjId,
                        name: pt.name,
                        deltaE: center.e - pt.e,
                        deltaN: center.n - pt.n,
                        deltaH: center.h - pt.h
                    });
                    yield models.AngleCoorDiff.create({
                        prjId: prjId,
                        name: pt.name,
                        deltaE: center.e - pt.e,
                        deltaN: center.n - pt.n,
                        deltaH: center.h - pt.h
                    });
                }
            }
        }
    }
    this.redirect(`/project/${this.params.id}/sectionconfig`);
});


module.exports = router.routes();
